<template>
  <div class="box">
    <div class="p-menu flex">
      <div class="p-menu-left flex flex-left">
        <el-input v-model="queryParams.keywords" class="p-i1" placeholder="用户名/手机号" />
        <el-select v-model="queryParams.platformId" placeholder="平台" class="p-i3" style="height: 38px;"
          v-show="userData.username == 'root'">
          <el-option v-for="item in platformList" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>


        <el-button color="#FABD68" class="p-button" @click="query()">查询</el-button>
      </div>

      <div class="p-menu-right flex flex-right">
        <el-button color="#2CA6E0" class="p-button" @click="setDialogVisible()">新建</el-button>
      </div>
    </div>
    <div class="p-ul-box flex">
      <el-table :data="submitList" style="max-width: 100%" class="p-ul" v-loading="loading" @row-click="handleRowClick"
        @click.stop.prevent>
        <el-table-column prop="id" label="序号" align="center" />
        <el-table-column prop="username" label="姓名" align="center " />
        <el-table-column prop="phone" label="手机" align="center " width="120" />
        <el-table-column prop="platformId" label="所属平台" width="120" :show-overflow-tooltip="true" align="center ">
          <template #default="scope">
            {{ getPlatformId(scope.row.platformId) }}
          </template>
        </el-table-column>
        <el-table-column prop="icon" label="角色" width="120" :show-overflow-tooltip="true" align="center ">
          <template #default="scope">
            {{ getRoleId(scope.row.roleId) }}
          </template>
        </el-table-column>
        <el-table-column prop="registerTime" label="注册时间" align="center " />


        <el-table-column label="审核状态" align="center">
          <template #default="scope">
            <el-button link type="info" size="small" @click="setPass(scope.row)" @click.stop.prevent><text
                :class="scope.row.audit ? '' : 'red'">{{ scope.row.audit ? '已审核' : '未审核' }}</text></el-button>
          </template>
        </el-table-column>

        <el-table-column label="账号状态" align="center">
          <template #default="scope">
            <text>{{ scope.row.enable ? '正常' : '冻结' }} </text>
          </template>
        </el-table-column>



        <el-table-column label="操作" align="center " width="150">
          <template #default="scope">
            <el-button link type="info" size="small" @click="setEnable(scope.row)" @click.stop.prevent><text
                :class="scope.row.enable ? '' : 'red'">{{ scope.row.enable ? '冻结' : '解冻' }}</text></el-button>

            <el-button link type="danger" size="small" style="color:red;" @click="userDelete(scope.row)"
              @click.stop.prevent>删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="message" v-show="userForm">
        <div class="m-headline">编辑信息</div>
        <div class="flex" style="margin-bottom: 20px;">
          <img class="m-headimg" :src="userinfo.avatar == null ? './img/userhome.png' : userinfo.avatar" />
          <div class="m-name">
            <div class="flex">
              <input class="name" v-model="userinfo.username" />
              <img class="m-x" :src="'./img/b1.png'" />
            </div>
            <div class="flex">
              <input class="phone" v-model="userinfo.phone" />
              <img class="m-x" :src="'./img/b1.png'" />
            </div>
          </div>
        </div>

        <!-- 表单 -->
        <el-form :model="userinfo" label-width="50px" class="input-box">


          <el-form-item label="性别">
            <el-col :span="9">
              <el-select v-model="userinfo.gender" placeholder="性别">
                <el-option v-for="item in genderSelect" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-col>
            <el-col class="line" :span="4" style="text-align: center;">年龄</el-col>
            <el-col :span="9">
              <el-input v-model="userinfo.age" placeholder="年龄" />
            </el-col>
          </el-form-item>
          <el-form-item label="平台" v-show="userData.username == 'root'">
            <el-select v-model="userinfo.platformId" placeholder="平台" disabled>
              <el-option v-for="item in platformList" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="角色">
            <el-select v-model="userinfo.roleId" placeholder="角色">
              <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="备注">
            <el-input v-model="userinfo.remark" class="" type="text" placeholder="备注" />
          </el-form-item>

        </el-form>




        <el-button color="#2CA6E0" class="m-button p-button" v-show="userinfo.id != null"
          @click="postUser()">确定</el-button>
      </div>


    </div>

    <div class="p-end flex">
      <div class="flex-left">共有{{ total }}项数据</div>
      <el-pagination class="flex-right" style="margin-right:50px;" v-model:current-page="queryParams.page"
        @current-change="currentChange" v-model:page-size="queryParams.size" layout="prev, pager, next, jumper"
        :total="total" />
    </div>

    <!-- 新增or编辑 -->
    <el-dialog v-model="dialogVisible" :title="visibleTitle" width="558">
      <div class="uploading-img">
        <el-upload class="avatar-uploader"   :data="proxy.$fileAvatar" name="file"
          accept="image/png,image/jpg,image/jpeg" :show-file-list="false"
          :action="config.baseUrl + proxy.$urlApi.toolkit.upload" :on-success="handleAvatarSuccessIcon">
          <img v-if="from.avatar" :src="from.avatar" class="avatar">
          <div v-else class="flex-s" style="width: 90px;height: 90px;">+</div>
        </el-upload>
      </div>

      <el-form :model="from" label-width="120px">
        <el-form-item label="姓名">
          <el-col :span="9">
            <el-input v-model="from.username" class="" placeholder="姓名" />
          </el-col>
          <el-col class="line" :span="4" style="text-align: center;">电话</el-col>
          <el-col :span="9">
            <el-input v-model="from.phone" class="" placeholder="电话" />
          </el-col>
        </el-form-item>
        <el-form-item label="性别">
          <el-col :span="9">
            <el-select v-model="from.gender" placeholder="性别">
              <el-option v-for="item in genderSelect" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-col>
          <el-col class="line" :span="4" style="text-align: center;">年龄</el-col>
          <el-col :span="9">
            <el-input v-model="from.age" class="" type="number" placeholder="年龄" />
          </el-col>
        </el-form-item>
        <el-form-item label="平台" v-if="false">
          <el-select v-model="from.platformId" placeholder="平台">
            <el-option v-for="item in platformList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="from.roleId" placeholder="角色">
            <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="from.password" placeholder="密码" type="password" />
        </el-form-item>
      </el-form>


      <template #footer>

        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="postSubmit">
            确定
          </el-button>
        </span>
      </template>

    </el-dialog>


    <el-dialog v-model="passVisible" title="审核用户" width="300">
      <span class="passBox">
        <div class="passText">{{ passTitle }}</div>
        <el-button @click="passVisible = false">取消</el-button>
        <el-button type="danger" @click="passAudit(false)"> 拒绝审核 </el-button>
        <el-button type="success" @click="passAudit(true)"> 通过审核 </el-button>
      </span>
    </el-dialog>




  </div>
</template>

<script setup>

import {
  ref,
  getCurrentInstance,
  onMounted,
  watchEffect,
  computed,
} from "vue";

import { ElMessage } from 'element-plus'
import config from '@/config';
// import { fr } from "element-plus/es/locale";


const {
  proxy
} = getCurrentInstance();

const userData = ref({});

const loading = ref(false);
const platformName = ref('');
//查询条件
const queryParams = ref({
  keywords: null,
  userame: null,
  platformId: null,
  remark: null,
  enable: null,
  size: 30,
  page: 1,
})

//新增
const from = ref({
  id: null,
  username: null,
  platformId: null,
  password: null,
  roleId: null,
  code: null,
  uri: null,
  icon: null,
  cover: null,
  remark: null,
  enable: null,
  avatar: null,
})

//用户基本信息
const userinfo = ref({
  id: null,
  username: null,
  password: null,
  platformId: null,
  gender: null,
  pass: null,
  remark: null,
  avatar: null,
})

const userForm = ref(false);
const pass = ref(false);
const passVisible = ref(false);
const passTitle = ref('');
const roleList = ref();//角色数据
//性别选择器
const genderSelect = ref([
  { value: 1, label: '男' },
  { value: 2, label: '女' }
])

const headers = computed(() => {
  let tokenData = localStorage.getItem('TOKENDATA');
  if (tokenData) {
    tokenData = tokenData ? JSON.parse(tokenData) : null;
    return { "Authorization": tokenData.token_type + ' ' + tokenData.access_token };
  } else return {};
})

watchEffect(() => {
  getUser();
})
onMounted(() => {
  getPlatformList();
  getSubmitList();
});


async function getUser() {
  const savedData = localStorage.getItem('USERINFO');
  const obj = JSON.parse(savedData);
  userData.value = obj;
  if (userData.value.platform != null) {
    // console.log("目前的值:")
    // console.log(obj)
    platformName.value = userData.value.platform.name;
    from.value.platformId = userData.value.platform.id;
    queryParams.value.platformId = userData.value.platform.id;
  }
  getRole();
}





const submitList = ref([]);//集合数据
const total = ref(0);

function getSubmitList() {//获取列表数据
  const data = queryParams.value;
  loading.value = true;
  proxy.$Request.get(proxy.$urlApi.user.listPage, data)
    .then((res) => {

      if (res.data.code != 200) {
        ElMessage({
          message: row.msg,
          type: 'error',
        })
      } else {
        total.value = res.data.data.total;
        submitList.value = res.data.data.list;
        getRole();
      }
      loading.value = false;
    }).catch(error => {
      loading.value = false;
    });
}


function query() {
  queryParams.value.page = 1;
  getSubmitList();
}



function handleAvatarSuccessIcon(res, file) {
  if (res.code == 200) {
    from.value.avatar = res.data;
  } else {
    ElMessage({
      message: res.msg,
      type: 'error',
    })
  }

}

//启动状态修改
function setEnable(row) {
  loading.value = true;
  const data = {
    id: row.id,
    enable: !row.enable
  }
  proxy.$Request.post(proxy.$urlApi.user.enable, data)
    .then((res) => {
      if (res.data.code != 200) {
        ElMessage({
          message: row.msg,
          type: 'error',
        })
      } else {
        getSubmitList();
      }
      loading.value = false;
    }).catch(error => {
      // 处理 Promise 拒绝的情况
      loading.value = false;
    });
}

//删除用户
function userDelete(row) {
  loading.value = true;
  const data = {
    id: row.id
  }
  proxy.$Request.delete(proxy.$urlApi.user.delete, data)
    .then((res) => {
      if (res.data.code != 200) {
        ElMessage({
          message: row.msg,
          type: 'error',
        })
      } else {
        getSubmitList();
        ElMessage({
          message: row.username + '删除成功',
          type: 'success',
        })
      }

      loading.value = false;
    }).catch(error => {
      // 处理 Promise 拒绝的情况
      loading.value = false;
    });
}


//新增or编辑
const dialogVisible = ref(false)
const visibleTitle = ref('');
function setDialogVisible(index) {
  if (index == null) {
    reset();
    visibleTitle.value = "新增"
    from.value.platformId = queryParams.value.platformId
  } else {
    from.value = index;
    visibleTitle.value = "编辑"
  }
  getRole();
  dialogVisible.value = true;
}


//


function handleRowClick(row) {
  userForm.value = true;
  const data = {
    id: row.id,
    username: row.username,
    password: row.password,
    phone: row.phone,
    platformId: row.platformId,
    gender: row.gender,
    pass: row.pass,
    remark: row.remark,
    roleId: row.roleId,
  };
  userinfo.value = data;
}



function postUser() {
  if (userinfo.value.id == null) {
    return
  }
  proxy.$Request.post(proxy.$urlApi.user.submit, userinfo.value)
    .then((res) => {
      if (res.data.code == 200) {
        getSubmitList();
        ElMessage({
          message: userinfo.value.username + '更新完成',
          type: 'success',
        })
        dialogVisible.value = false
      } else {
        ElMessage({
          message: res.data.msg,
          type: 'error',
        })
      }

    }).catch(error => {
      ElMessage({
        message: userinfo.value.username + '更新失败',
        type: 'error',
      })
    });
}

async function getRole() {
  const data = {
    platformId: userinfo.value.platformId
  }
  proxy.$Request.get(proxy.$urlApi.role.list, data)
    .then((res) => {
      if (res.data.code == 200) {
        roleList.value = res.data.data
      } else {
        ElMessage({
          message: res.data.msg,
          type: 'error',
        })
      }
    }).catch(error => {
      ElMessage({
        message: res.data.msg,
        type: 'error',
      })
    });
}


function setPass(row) {
  if (row.audit) {
    return
  }
  passVisible.value = true;
  passTitle.value = row.username + '是否通过审核';
  userinfo.value = row;
}
//审核
function passAudit(pass) {
  userinfo.value.pass = pass;
  dialogVisible.value = true
  if (userinfo.value.audit) {
    proxy.$Request.post(proxy.$urlApi.user.audit, userinfo.value
    )
      .then((res) => {
        if (res.data.code != 200) {
          ElMessage({
            message: res.msg,
            type: 'success',
          })
        } else {
          ElMessage({
            message: userinfo.value.username + '审核完毕',
            type: 'success',
          })
        }
        dialogVisible.value = false
        getSubmitList();
        passVisible.value = false;

      }).catch(error => {
        ElMessage({
          message: userinfo.value.username + '更新失败',
          type: 'error',
        })
        passVisible.value = false;

      });
  }

}

//id
function getPlatformId(id) {
  const data = platformList.value
  for (let i = 0; data.length > i; i++) {
    if (data[i].id == id) {
      return data[i].name
    }
  }
}







function postSubmit() {//提交
  // let namePinyin = vPinyin.chineseToPinYin(salesmanName
  dialogVisible.value = true
  proxy.$Request.post(proxy.$urlApi.user.submit, from.value)
    .then((res) => {
      if (res.data.code == 200) {
        getSubmitList();
        ElMessage({
          message: visibleTitle.value + '完成',
          type: 'success',
        })
      } else {
        ElMessage({
          message: res.data.msg,
          type: 'error',
        })
      }
      dialogVisible.value = false

    }).catch(error => {
    });

}


function reset() {//重置数据

  from.value = {
    id: null,
    username: null,
    password: null,
    platformId: null,
    roleId: null,
    phone: null,
    avatar: null,
    gender: null,
    age: null,
    remark: null,
    enable: true,
  }
  if (userData.value.platform != null) {
    from.value.platformId = userData.value.platform.id;
  }
}




//获取平台集合
const platformList = ref([]);
function getPlatformList() {
  const data = {
    enable: 1
  }
  proxy.$Request.get(proxy.$urlApi.platform.list, data)
    .then((res) => {
      platformList.value = res.data.data;
    }).catch(error => {
    });
}

//分页
function currentChange(num) {
  queryParams.value.page = num;
  getSubmitList();
}


function getRoleId(id) {
  //console.log(roleList.value);
  const data = roleList.value
  for (let i = 0; data.length > i; i++) {
    if (data[i].id == id) {
      return data[i].name
    }
  }
}



</script>


<style lang="scss">
.p-menu {
  background: #F9FAFA;
  margin: 30px;
  height: 40px;
}

.p-i1,
.p-i2,
.p-i3 {
  margin-right: 10px;
  color: black;
  height: 40px;

}

.p-i2 {
  width: 194px;
}

.p-i3 input {
  height: 38px;
}

.p-i1 {
  width: 271.49px;
}


.p-button {
  color: white;
  width: 92px;
  height: 40px;
}

.el-input__inner::placeholder {
  color: #999 !important;
}


.p-ul-box {
  padding: 0 30px;
}

//列表

.el-table__inner-wrapper {
  height: calc(100vh - 300px);
}

.full .el-table__inner-wrapper {
  height: calc(100vh - 210px);
}

.is-leaf.el-table__cell {
  background: #E7F0F3 !important;

}

.el-table__cell {
  white-space: nowrap;
  /* 防止文本换行 */
  overflow: hidden;
  /* 超出部分隐藏 */
}

.cell {
  white-space: nowrap;
  /* 防止文本换行 */
  overflow: hidden;
  /* 超出部分隐藏 */
}

.el-table__row:nth-child(odd) {
  background-color: #FFFFFF;
  /*奇数行的背景颜色*/
}

.el-table__row:nth-child(even) {
  background-color: #F9FAFA;
  /*偶数行的背景颜色*/
}


.p-end {
  font-size: 10px;
  padding-left: 30px;
  color: #9A9DAA;
  margin-top: 20px;
}

.el-dialog__header {
  font-size: 16px;
}

.el-dialog__footer {
  font-size: 16px;
}

.el-input__wrapper {
  font-size: 16px;
}

//信息框
.message {
  font-size: 16px;
  width: 510px;
  height: calc(100vh - 300px);
  padding: 20px;

  .m-headline {
    color: #9A9DAA;
    font-weight: 700;
  }

  .m-headimg {
    width: 90px;
    height: 90px;
    margin-top: 35px;
    margin-right: 21px;
    border-radius: 5px;
  }

  .m-name {
    margin-top: 35px;
    white-space: nowrap;
    /* 防止文本换行 */
    overflow: hidden;
    align-items: center;

    .m-x {
      width: 24px;
      height: 24px;
      margin: 3px 0;
    }

    .name {
      font-size: 36px;
      color: #000000;
      margin-bottom: 16px;
      width: 170px;
      border: none;
      outline: none;
      /* 去除聚焦时的边框 */
      background: none;
    }

    .phone {
      font-size: 24px;
      color: #9A9DAA;
      width: 170px;
      border: none;
      outline: none;
      /* 去除聚焦时的边框 */
      background: none;

    }
  }

  .m-button {
    float: right;
    margin-top: 180px;
  }

}


.uploading-img {

  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 40px;

  img {
    width: 90px;
    height: 90px;
  }

  .head-img {
    border: solid #000000 1px;
    width: 90px;
    height: 90px;
    line-height: 90px;
    text-align: center;
  }

}

.passBox {
  button {
    margin: 0 5px;
  }

  .passText {
    width: 100%;
    margin-bottom: 30px;
    text-align: center;
    font-size: 20px;
  }
}
</style>

